package com.mjk.common.core.jdbc.ibatis.typehandler.handler;


import com.mjk.common.core.jdbc.ibatis.typehandler.BaseHandler;
import com.mjk.common.tools.logger.BizLogger;
import com.mjk.common.util.ObjectUtils;
import org.springframework.util.FileCopyUtils;

import javax.sql.rowset.serial.SerialBlob;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.sql.Blob;
import java.sql.SQLException;

public class BlobHandler implements BaseHandler<Blob> {

	@Override
	public String resovleToString(Field f,Blob t) {			
		try {
			if(ObjectUtils.isEmpty(t)){
                return null;
			}
			return blobToString(t);
		} catch (SQLException | IOException e) {			
			BizLogger.error(e);
		}
		return "";
	}

	@Override
	public Blob resovleResult(Object o) {
		if (o instanceof Blob blob)
			return blob;
		try {
			return new SerialBlob(o.toString().getBytes());
		} catch (Exception e) {
			return null;
		}
	}

	private String blobToString(Blob blob) throws SQLException, IOException {
		InputStream is=blob.getBinaryStream();
		byte[] bs=FileCopyUtils.copyToByteArray(is);
		return bytesToHexString(bs);
	}
	
	private String bytesToHexString(byte[] src) {
		StringBuilder stringBuilder = new StringBuilder();
		if (src == null || src.length == 0) {
			return null;
		}
        for (byte b : src) {
            int v = b & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
		return stringBuilder.toString();
	}
}
